package com.ruoyi.business.controller.calcuate;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.base.controller.BaseController;
import com.ruoyi.base.enums.unit.UnitEnum;
import com.ruoyi.base.exception.CustomException;
import com.ruoyi.base.pojo.HttpResult;
import com.ruoyi.business.pojo.item.ItemQuery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Optional;

/**
 * 计算
 *
 * @author Administrator
 */
@Slf4j
@Api(tags = "计算")
@RestController
@RequestMapping("/calcuate")
public class CalCuateController extends BaseController {
    /**
     * 获取单位列表
     */
    @ApiOperation("计算")
    @GetMapping("/do")
    public HttpResult<String> calcuate(@ApiParam("[{'amount': 1, 'price': 1, 'unit': 1}]") String query) {
        if (StringUtils.isBlank(query)) {
            throw exception("参数为空");
        }

        List<ItemQuery> list = JSONArray.parseArray(query, ItemQuery.class);
        if (CollectionUtils.isEmpty(list)) {
            throw exception("参数为空");
        }

        BigDecimal result = BigDecimal.ZERO;
        for (ItemQuery item : list) {
            UnitEnum unitEnum = Optional.ofNullable(UnitEnum.ofCode(item.getUnit())).orElseThrow(() -> new CustomException("单位不存在"));
            result = result.add(item.getPrice().multiply(item.getAmount()).multiply(unitEnum.getAmount()));
        }

        return data(result.setScale(2, RoundingMode.HALF_UP).toString());
    }
}
